package com.lizk.zookeeper;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;

/**
 * Hello world!
 *
 */
public class App implements Watcher
{

	ZooKeeper zk = null;

	public static void main( String[] args ) throws IOException, KeeperException, InterruptedException
	{
		App a = new App();
		a.conn();

		TimeUnit.SECONDS.sleep(5);
	}

	public void conn() throws IOException, KeeperException, InterruptedException{
		zk = new ZooKeeper("10.10.10.116:2181", 3000, this);
		Stat stat = zk.exists("/test", true);
		if(stat != null){
			zk.delete("/test", -1);
			zk.exists("/test", true);
		}
		System.out.println("create:" + zk.create("/test", "test".getBytes(), Ids.OPEN_ACL_UNSAFE , CreateMode.PERSISTENT));
		zk.exists("/test", true);
		stat = zk.setData("/test", "test2".getBytes(),0);
		System.out.println(stat.getAversion());
		System.out.println(stat.getVersion());
		System.out.println(stat.getCversion());
		System.out.println(stat.getCtime());

		zk.exists("/test", true);
		zk.getChildren("/test", true);
		System.out.println("create:" + zk.create("/test/1", "1".getBytes(), Ids.OPEN_ACL_UNSAFE , CreateMode.PERSISTENT));



	}

	@Override
	public void process(WatchedEvent event) {
		if(event.getState() == KeeperState.SyncConnected){
			if(event.getType() == null){
				System.out.println("链接成功");
			}else{
				if( event.getType() == EventType.NodeChildrenChanged){
					System.out.println("子节点变化");
					System.out.println(event.getPath());

				}

				if( event.getType() == EventType.NodeCreated){
					System.out.println("节点创建");
					System.out.println(event.getPath());

				}
				if( event.getType() == EventType.NodeDataChanged){
					System.out.println("节点数据变化");
					System.out.println(event.getPath());
					System.out.println(event.getWrapper());
				}
				if( event.getType() == EventType.NodeDeleted){
					System.out.println("节点呗删除");
					System.out.println(event.getPath());
					System.out.println(event.getWrapper());
				}
			}
		}
	}


}
